/**
 * 审批表单
*/
// import Item from "antd/lib/list/Item";
import "./approveForm.css";

import { useRequest, useUpdate } from "ahooks";
import React, { Suspense, useEffect, useRef, useState } from "react";
import { Drawer, Button} from 'antd';
import { InjectProvider } from "../../framework/common/context/inject-context";
import { useForm } from "../../framework/common/context/metadata-context";
import eventBus, { useSubscribe } from "../../framework/common/eventBus";
import request from "../../framework/common/utils/request";
import message from "../../framework/common/utils/message";
import set from "lodash/set";

import { initAllStepData } from "../../RuntimeForm/ApproveStep/stepUtility";//清洗后端返回的步骤信息
import { submitApproveForm, addStepApprove, showInitiateSteps, beforeApproeValidate } from "./submitApproveForm";//审批提交事件
import { formDataReload } from "../Header/businessBtnUtils";

import ApproveButtonList,{ ButtonList} from "./ApproveButtonList";//审批按钮组件
import ModalStepEdit from "../../RuntimeForm/ApproveStep/ModalStepEdit1";//确认步骤弹出框组件
import ModalSignPassword from "../../RuntimeForm/ApproveStep/ModalSignPassword";//签章弹出框组件
import { validarelationProcessList } from "../../RuntimeForm/RelationProcess1/RelationProcess1";//校验关联流程
import { NegotiateLogWrap } from "../../RuntimeForm/ApproveStep/components/NegotiateLogWrap";
import { setConsultRead } from "./submitApproveForm";//重置回复协商的红点点
import { getApproveBtnName } from "../../RuntimeForm/ApproveStep/stepUtility";

/*下面是各个审批类型表单*/
import InitiateForm from "./ApproveForm/SubInitiateForm";/*同意表单*/
import PassForm from "./ApproveForm/PassForm";/*同意表单*/
import RollBackForm from "./ApproveForm/RollBackForm";/*驳回表单*/
import BookForm from "./ApproveForm/BookForm";
import VoteForm from "./ApproveForm/VoteForm";
import ConsultForm from "./ApproveForm/ConsultForm";
import ReplyConsultForm from "./ApproveForm/ReplyConsultForm";
import AssignedForm from "./ApproveForm/AssignedForm";
import TerminateForm from "./ApproveForm/TerminateForm";
import AddSignForm from "./ApproveForm/AddSignForm";
import CancelForm from "./ApproveForm/CancelForm";//作废表单

export default function ({ 
    
}) {

    const metadataManager = useForm().root;
    const { data: tplData, urlPrefix, params} = useForm().root;
    const [visible, setVisible] = useState(false);//抽屉显示状态
    //const [visible, setVisible] = useState(true);//抽屉显示状态
    const [btnVisible, setBtnVisible] = useState(true);//审批按钮显示状态
    //const [btnVisible, setBtnVisible] = useState(false);//审批按钮显示状态
    const [approveType, setApproveType] = useState(tplData.ApproveButtons[0].OperationCode);//审批类型
    const [approveText, setApproveText] = useState(tplData.ApproveButtons[0].ButtonName);//审批按钮名称
    const [btnListLoading, setBtnListLoading] = useState(false);//审批类型按钮列表状态
    const [loading, setLoading] = useState(false);//审批确定按钮loading状态
    const [addStepLoading, setAddStepLoading] = useState(false);//添加步骤按钮loading状态
    const [editModelInfo, setEditModelInfo] = useState({
        showStepEditModal: false//确认步骤路径是否显示
    });//确认步骤路径
    const [signModelInfo, setSignModelInfo] = useState({
        showSignModelModal: false//确认签章是否显示
    });//签章密码


    const formRef = useRef();//穿透子组件的form对象给当前父组件，用于更新字段等信息

    if(!tplData.__approveForm__){
        tplData.__approveForm__ = {}
    };
    if(!tplData.__opinionList__){
        tplData.__opinionList__ = {}
    };

    let ApproveForm = null;
    switch(approveType){
        case "Initiate"://发起
            ApproveForm = <InitiateForm
                                tplData={tplData}
                                urlPrefix={urlPrefix}
                                formRef={formRef}
                                approveType={approveType}
                                approveText={approveText}
                            ></InitiateForm>
            break;
        case "Pass"://同意
            ApproveForm = <PassForm
                tplData={tplData}
                urlPrefix={urlPrefix}
                formRef={formRef}
                approveType={approveType}
                approveText={approveText}
            ></PassForm>
            break;
        case "RollBack"://驳回
            ApproveForm = <RollBackForm
                tplData={tplData}
                urlPrefix={urlPrefix}
                formRef={formRef}
                approveType={approveType}
                approveText={approveText}
            ></RollBackForm>
            break;
        case "Book"://归档
            ApproveForm = <BookForm
                tplData={tplData}
                urlPrefix={urlPrefix}
                formRef={formRef}
                approveType={approveType}
                approveText={approveText}
            ></BookForm>
            break;
        case "Consult"://发起协商
            ApproveForm = <ConsultForm
                tplData={tplData}
                urlPrefix={urlPrefix}
                formRef={formRef}
                approveType={approveType}
                approveText={approveText}
            ></ConsultForm>
            break;
        case "ReplyConsult"://回复协商
            ApproveForm = <ReplyConsultForm
                tplData={tplData}
                urlPrefix={urlPrefix}
                formRef={formRef}
                approveType={approveType}
                approveText={approveText}
            ></ReplyConsultForm>
            break;
        case "Assigned"://交办
            ApproveForm = <AssignedForm
                tplData={tplData}
                urlPrefix={urlPrefix}
                formRef={formRef}
                approveType={approveType}
                approveText={approveText}
            ></AssignedForm>
            break;
        case "Vote"://表决
            ApproveForm = <VoteForm
                tplData={tplData}
                urlPrefix={urlPrefix}
                formRef={formRef}
                approveType={approveType}
                approveText={approveText}
            ></VoteForm>
            break;
        case "Terminate"://终止
            ApproveForm = <TerminateForm
                tplData={tplData}
                urlPrefix={urlPrefix}
                formRef={formRef}
                approveType={approveType}
                approveText={approveText}
            ></TerminateForm>
            break;
        case "AddSign"://加签
            ApproveForm = <AddSignForm
                tplData={tplData}
                urlPrefix={urlPrefix}
                formRef={formRef}
                approveType={approveType}
                approveText={approveText}
            ></AddSignForm>
            break;
        case "Cancel"://作废
            ApproveForm = <CancelForm
                tplData={tplData}
                urlPrefix={urlPrefix}
                formRef={formRef}
                approveType={approveType}
                approveText={approveText}
            ></CancelForm>
            break;
        default://其他审批状态
            ApproveForm= <p>{approveText}-{approveType}类型开发中</p>
            break;
    }

    //获取按钮信息 默认审批意见 常用意见 以及其他信息
    function getApproveBtnInfo(approveType){
        if(!approveType){
            console.log("缺少approveType，无法获得审批按钮对应信息");
            return;
        }
        var self = this;
        var sendData = {
            action: approveType,
            package_id:tplData.package_id,
            proc_id: tplData.ProcessInfo.ProcessGuid,
            node_id: tplData.NodeInfo.node_id,
            step_type: tplData.StepInfo.step_type,
            opinion: tplData.NodeInfo && tplData.NodeInfo.opinion,
            is_end_task: tplData.NodeInfo && tplData.NodeInfo.is_end_task,
            is_sub_process_start: params.ParentProcess && params.ParentProcess.IsSubProcessStart
        };
        if(tplData.NodeInfo && tplData.NodeInfo.expand_opinion){
            sendData.expand_opinion = tplData.NodeInfo.expand_opinion;
        }
        setBtnListLoading(true);
        return request({
            data: sendData,
            method: 'POST',
            url: "/flowinstance/approval/get-approve-options"
        })
    }

    //更新表单数据，用于同时更新form数据源和tplData数据源
    function upDateFormDate( {opinionList, approveType, expandOpinions, ...formValues}){
        //1.更新表单字段
        formRef.current.setFieldsValue(formValues);
        //2.更新tplData
        tplData.__approveForm__[approveType] = {
            ...tplData.__approveForm__[approveType], 
            ...formValues
        };
        
        //3.更新常用意见
        if(opinionList){
            tplData.__opinionList__[approveType] = opinionList;
        }
        eventBus.publish("cyyj.update." + approveType);

        //4.更新扩展意见
        //更新路径为 tplData.__extraOptions__.approveType.expandOpinions = expandOpinions;
        // expandOpinions 为扩展意见radiogroup的选项信息
        // tplData.__extraOptions__ 内緩存字段的配置文件，为未来其他字段做扩展，如果有其他字段需要
        if(expandOpinions){
            set(tplData, "__extraConfig__." + approveType + ".expandOpinions", expandOpinions);
        };
        eventBus.publish("extraConfig.update." + approveType);
    }

    //审批按钮切换
    function btnTab({
        approveType,//审批类型
        text//审批按钮名称
    }){
        tplData.__approveType__ = approveType;//缓存当前状态
        let approveFormData = tplData?.__approveForm__?.[approveType];//对应的审批类型表单数据
        if(approveFormData){//如果已经初始化过表单，直接切换显示状态

            //1.先处理好公共字段数据回填
            let commonData = tplData.__approveFormCommonData__;//缓存的“审批类型表单”公共字段value
            if(commonData){
                Object.keys(approveFormData).forEach(function (formKey){//遍历对应的审批表单字段
                    if(commonData.hasOwnProperty(formKey)){//如果缓存里面存在值
                        approveFormData[formKey] = commonData[formKey];//把缓存的值回填
                    }
                })
            }
            //2.再切换表单显示隐藏状态，避免数据没跟着更新
            setApproveType(approveType);//更新审批表单显示隐藏
            setApproveText(text);//更新审批标题名称
            return;
        }else{//没初始化过表单，发请求拿一下最新的按钮数据
            setApproveType(approveType);//更新审批表单显示隐藏
            setApproveText(text);//更新审批标题名称
            getApproveBtnInfo(approveType).then(function(result){
                setBtnListLoading(false);
                if (result.code == 1) {
                    if (result.data) {
                        upDateFormDate({
                            approveType: approveType,
                            opinion: result.data.DefaultOption,//默认审批意见
                            opinionList:result.data?.OpinionList //常用意见列表
                        });//更新审批表单数据
                    }
                    switch(approveType){
                        case "Pass"://同意
                            // result.data.ExpandOpinion = [
                            //     {
                            //         label: "111",
                            //         value: 2
                            //     },
                            //     {
                            //         label: "222",
                            //         value: 3
                            //     }
                            // ]
                            if(result.data?.ExpandOpinion?.length > 0){
                                let expand_opinion = "";
                                result.data.ExpandOpinion.find((item)=>{
                                    if(item.is_default === "true"){
                                        expand_opinion = item.value;
                                    }
                                })
                                upDateFormDate({
                                    approveType: approveType,
                                    expandOpinions: result.data.ExpandOpinion,//扩展意见radio数据源
                                    expand_opinion: expand_opinion//扩展意见默认值
                                });//更新审批表单数据
                            }
                            break;
                        case "RollBack"://驳回
                            upDateFormDate({
                                approveType: approveType,
                                radio_back: result.data.radio_back ? String(result.data.radio_back) : "0",//打回到
                                roll_back_type: result.data.roll_back_type ? result.data.roll_back_type : null,//驳回方式
                                step_id: result.data.step_id ? result.data.step_id : null,//默认审批意见
                                opinionList:result.data?.OpinionList //常用意见列表
                            });//更新审批表单数据
                            break;
                        case "Book"://归档
                            let data={
                                approveType: approveType,
                                opinionList:result.data?.OpinionList //常用意见列表
                            }
                            if(result?.data?.archived_directory_id){
                                data.archived_directory_id= result?.data?.archived_directory_id //归档目录
                            }
                            upDateFormDate(data);//更新归档表单数据
                            break;
                        case "Consult"://发起协商

                            setConsultRead({
                                tplData: tplData
                            });//重置回复协商小点点

                            upDateFormDate({
                                approveType: approveType,
                                to:result?.data?.selectConsult,//默认审批意见
                                opinionList:result.data?.OpinionList //常用意见列表
                            });//更新归档表单数据
                            break;
                        case "ReplyConsult"://回复协商
                            upDateFormDate({
                                approveType: approveType,//默认审批意见
                                opinionList:result.data?.OpinionList //常用意见列表
                            });//更新归档表单数据
                            break;
                        case "Assigned"://交办
                            upDateFormDate({
                                approveType: approveType,
                                assigned: result?.data?.selectAssigned,//默认审批意见
                                opinionList:result.data?.OpinionList //常用意见列表
                            });//更新归档表单数据
                            break;
                        case "Vote"://表决
                            upDateFormDate({
                                approveType: approveType,
                                voted_status: result?.data?.voted_status || "1",//默认审批意见
                                opinionList:result.data?.OpinionList //常用意见列表
                            });//更新归档表单数据
                            break;
                        case "AddSign"://加签
                            upDateFormDate({
                                approveType: approveType,
                                opinionList:result.data?.OpinionList, //常用意见列表
                                add_sign_after:result.data?.add_sign_after || "0",  //加签后
                                add_sign_users:result.data?.selectAddSign || []  //加签人

                            });//更新归档表单数据
                            break;
                        default:
                            break;
                    }
                } else {
                    message.info({
                        content: result.message,
                        afterClose:function(){
                            
                        }
                    });
                }
            },function(){
                setBtnListLoading(false);
                message.info({
                    content: "获取常用意见列表失败。",
                    afterClose:function(){
                        
                    }
                });
            });
        }
    }

    //其他组件更新当前组件按钮loading状态
    useSubscribe("setAproveBtnLoading.update", (data)=>{
        if(data !== undefined){
            setLoading(data);
        }else{//没传data，默认去掉按钮loading状态
            setLoading(false);
        }
    },[setLoading]);
    useSubscribe("setAddStepLoading.update", (data)=>{
        if(data !== undefined){
            setAddStepLoading(data);
        }else{//没传data，默认去掉按钮loading状态
            setAddStepLoading(false);
        }
    },[setAddStepLoading]);

    //其他组件调用发起审批
    useSubscribe("doApprove.update", ()=>{
        submitApproveForm({
            tplData: tplData,
            params: params,
            urlPrefix: urlPrefix,

            enable_sign_pwd: false,//是否需要校验签证密码，二次调用审批，不需要校验，给false RollBack需要
            isValid: false,// 其他组件调用的发起，这里给空 RollBack 
            manual_execution: false,
            approveType: approveType,//approveType,//审批类型
            setLoading: setLoading//确定按钮的状态
        });//其他组件调用的发起审批
    },[approveType]);

    //显示签章密码弹框
    useSubscribe("showSignModal.update", (data)=>{
        if(!data){
            console.log("showSignModal.update 缺少data数据，不执行更新")
            return;
        }
        setSignModelInfo(data);
    });

    //更新各个审批类型公共字段数据
    useSubscribe("approveFormCommonData.update", (data)=>{
        if(!data){
            console.log("approveFormCommonData.update缺少data数据，不执行更新")
            return;
        }
        if(!tplData.__approveFormCommonData__){
            tplData.__approveFormCommonData__ = {};
        }
        tplData.__approveFormCommonData__ = {
            ...tplData.__approveFormCommonData__,
            ...data
        }//把审批组织的选中信息缓存起来，用于其他类型表单进行默认值回填
    });

    //监听要弹出确认路径对话框
    useSubscribe("showApproveStep.update", (stepData)=>{
        let stepInfo = initAllStepData({
            stepData: stepData,
            multiUserSelect: tplData.ProcessInfo.MultiUserSelect//是否需要默认选中多人步骤中的所有人;
        });
        if(!stepInfo){//如果校验失败，则return，不显示确认步骤路径
            return;
        }
        setEditModelInfo({
            ...editModelInfo, 
            ...{
                //步骤信息
                actual_steps: stepInfo.actual_steps,//不包括branch步骤
                approveSteps: stepInfo.approveSteps,//包括branch步骤，branch是选择分支步骤的信息
                validateResult: stepInfo.validateResult,//步骤错误信息
                showStepEditModal: true,//显示确认步骤弹出框
            }
        });//显示确认步骤路径弹框
    });

    return <>
        {
            btnVisible
            && <ApproveButtonList
                    btnListLoading={btnListLoading}
                    btnClick={({approveType, text})=>{
                        setVisible(true);//显示抽屉
                        setBtnVisible(false);//隐藏审批按钮
                        btnTab({
                            approveType: approveType,
                            text: text
                        });
                    }}
                ></ApproveButtonList>
        }
        <Drawer
            title={approveText}
            placement="right"
            className="myDrawer"
            onClose={()=>{
                //抽屉点击关闭
                setVisible(false);//隐藏抽屉
                setApproveType("");
                tplData.__approveType__ = "";
                setTimeout(function(){
                    setBtnVisible(true);//显示审批按钮
                }, 100)
                eventBus.publish("cancelALlRerquest");
            }}
            visible={visible}
            key={"right"}
            width={540}
            afterVisibleChange={(visible)=>{
                //抽屉动画结束后
                if(visible){//显示

                }else{//隐藏
                    
                }
            }}
        >
            {/*审批按钮*/}
            {
                !btnVisible
                && <ButtonList
                        btnListLoading={btnListLoading}
                        className={'absolute w-50px -left-50px top-4'}
                        approveType={approveType}
                        btnClick={({approveType, text})=>{
                            btnTab({
                                approveType: approveType,
                                text: text
                            });
                        }}
                    ></ButtonList>
            }

            {/*审批表单*/}
            {ApproveForm}
            <div className="text-right confirm-wrap">
                {
                    (approveType == 'Pass' && tplData.temporaryStepsSetting && tplData.temporaryStepsSetting.approve)
                    && <Button 
                        id="submit-approval-addstep" 
                        className="w-24"
                        loading={addStepLoading}
                        onClick={()=>{
                            setEditModelInfo({
                                showStepEditModal: true//显示确认步骤弹出框
                            });//显示确认步骤路径弹框
                            addStepApprove({
                                tplData: tplData,
                                params: params,
                                urlPrefix: urlPrefix,
                                approveType: approveType,
                                setLoading: setLoading,
                                setAddStepLoading: setAddStepLoading
                            });//添加步骤&&审批
                        }}
                    >添加步骤</Button>
                }
                <Button 
                    id="submit-approval" 
                    type="primary" 
                    className="w-24 ml-3" 
                    loading={loading}
                    onClick={()=>{

                        beforeApproeValidate({
                            form: formRef.current,
                            metadataManager: metadataManager,
                            tplData: tplData,
                            approveType: approveType,
                            validateSuccess:function(){//校验通过回调
                                var reInitiate = false;
                                tplData.ApproveButtons.forEach(function(btn) {
                                    if (btn['OperationCode'] == 'Pass' && btn['ButtonIcon'] == 'icon-faqi') {
                                        reInitiate = true;
                                    }
                                })
                                if(reInitiate || approveType === "Initiate"){//如果是重新发起 || 发起，需要同步业务数据后，再发起

                                    setLoading(true);//审批确定按钮loading
                                    formDataReload({
                                        form: metadataManager,
                                        tplData: tplData,
                                        params: params,
                                        urlPrefix: urlPrefix,
                                        success:function(){
                                            
                                            if(approveType === "Initiate"){//发起审批先显示确认步骤路径
                                                showInitiateSteps({
                                                    params: params,
                                                    tplData: tplData,
                                                    approveType: approveType,
                                                    setEditModelInfo: setEditModelInfo,
                                                    beforeAjax:function(){
                                                        
                                                    },
                                                    success:function(){
                                                        setLoading(false);//审批确定按钮loading
                                                    },
                                                    error:function(result){
                                                        setLoading(false);//审批确定按钮loading
                                                        if(result.message === "canceled"){
                                                            console.log('主动取消')
                                                        }else{
                                                            message.info({
                                                                content: "获取步骤路径失败",
                                                            });
                                                        }
                                                    }
                                                });
    
                                            }else{//其他类型直接发起
                                                setLoading(false);//审批确定按钮loading
                                                submitApproveForm({
                                                    isReinitiate: true,//重新发起
                                                    enable_sign_pwd: tplData.ProfileSign && tplData.ProfileSign.enable_sign == '1' && tplData.ProfileSign.enable_sign_pwd == '1',//开启了签章 RollBack需要
                                                    isValid: 'valid',// Pass需要，且这个位置一定要给 'valid'
                                                    manual_execution: false,
                                                    tplData: tplData,
                                                    params: params,
                                                    urlPrefix: urlPrefix,
                                                    approveType: approveType,
                                                    setLoading: setLoading//确定按钮的状态
                                                });
                                            }
                                        },
                                        error:function(){
                                            setLoading(false);//审批确定按钮loading
                                        }
                                    });
                                }else{
                                    submitApproveForm({
                                        enable_sign_pwd: tplData.ProfileSign && tplData.ProfileSign.enable_sign == '1' && tplData.ProfileSign.enable_sign_pwd == '1',//开启了签章 RollBack需要
                                        isValid: 'valid',// Pass需要，且这个位置一定要给 'valid'
                                        manual_execution: false,
                                        tplData: tplData,
                                        params: params,
                                        urlPrefix: urlPrefix,
                                        approveType: approveType,
                                        setLoading: setLoading//确定按钮的状态
                                    });
                                }
                            }
                        })

                    }}
                >确定</Button>
            </div>
            {
                (tplData.NodeInfo.consults && tplData.NodeInfo.consults.length > 0 && ["Consult", "ReplyConsult"].indexOf(approveType) >-1)
                && <>
                    <div className="pt-3 mt-3 mb-4  border-t text-color-666 border-gray-998">{getApproveBtnName({approveType:"Consult", btnText:"协商", tplData: tplData})}记录</div>
                    <NegotiateLogWrap tplData={tplData}></NegotiateLogWrap>
                </>
            }
        </Drawer>
        {
            editModelInfo.showStepEditModal && 
            <InjectProvider value={{checkList:{}}}>
                <ModalStepEdit
                    // key={editModelInfo.approveSteps}
                    showStepEditModal={editModelInfo.showStepEditModal}
                    actual_steps={editModelInfo.actual_steps}
                    approveSteps={editModelInfo.approveSteps}
                    validateResult={editModelInfo.validateResult}
                    model={"edit"}
                    tplData={tplData} 
                    params={params} 
                    urlPrefix={urlPrefix}
                    approveType={approveType}
                    handleCancel={()=>{
                        // getStepRef.current.cancel('sourceCancel');//取消获取流程请求
                        // setApproveBtnStatue(false);
                        setLoading(false);//取消按钮loading状态
                        setAddStepLoading(false);//添加步骤按钮loading状态
                        setEditModelInfo({
                            showStepEditModal: false
                        });//隐藏确认确认步骤路径弹出框
                    }}

                    handleApprove={()=>{
                        console.log('弹出框')
                        // initiateApprove({
                        //     steps: steps,
                        //     tplData: tplData,
                        //     params: params,
                        //     urlPrefix: urlPrefix
                        // })//发起流程
                    }}
                ></ModalStepEdit>
            </InjectProvider>
        }

        {
            signModelInfo.showSignModelModal
            && <ModalSignPassword
                showSignModelModal={signModelInfo.showSignModelModal}
                parentSetLoading={setLoading}
                handleCancel={()=>{
                    setSignModelInfo({
                        showSignModelModal: false//隐藏签章弹出框
                    });
                    setLoading(false);//取消按钮loading状态
                }}
            ></ModalSignPassword>
        }
    </>;
}